package gen.core.managers;

import gen.core.exceptions.GenException;
import gen.core.models.Template;
import gen.core.others.GenBeanProcess;
import gen.core.utils.GenUtils;

import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Connection;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.dbutils.BasicRowProcessor;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class TemplateManager {
	public Template[] list(Connection conn, String owner, String catagory) {
		String sql;
		QueryRunner runner = new QueryRunner();

		BeanListHandler<Template> handler = new BeanListHandler<Template>(Template.class, new BasicRowProcessor(new GenBeanProcess()));
		sql = "SELECT * FROM GEN_TEMPLATE WHERE OWNER = ? AND CATAGORY = ?";
		try {
			List<Template> aList = runner.query(conn, sql, handler, new Object[] { owner, catagory });
			return aList.toArray(new Template[0]);
		} catch (Exception ex) {
			throw new GenException(ex, "读取用户模板列表时，发生异常！");
		}
	}

	public Template load(Connection conn, String id) {
		String sql;
		QueryRunner runner = new QueryRunner();

		BeanHandler<Template> handler = new BeanHandler<Template>(Template.class, new BasicRowProcessor(new GenBeanProcess()));
		sql = "SELECT * FROM GEN_TEMPLATE WHERE ID = ?";
		try {
			return runner.query(conn, sql, handler, new Object[] { id });
		} catch (Exception ex) {
			throw new GenException(ex, "读取模板时，发生异常！模板ID=" + id + "！");
		}
	}

	public void save(Connection conn, Template theTemplate) {
		String sql;
		QueryRunner runner = new QueryRunner();

		try {
			if (StringUtils.isBlank(theTemplate.getId())) {
				sql = "INSERT INTO GEN_TEMPLATE VALUES(?,?,?,?,?,?,?,?)";
				theTemplate.setId(UUID.randomUUID().toString());
				theTemplate.setCreateTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				theTemplate.setModifiedTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				runner.update(conn, sql, theTemplate.getId(), theTemplate.getName(), theTemplate.getDescription(), theTemplate.getCatagory(),
						theTemplate.getContent(), theTemplate.getOwner(), theTemplate.getCreateTime(), theTemplate.getModifiedTime());
			} else {
				theTemplate.setModifiedTime(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
				sql = "UPDATE GEN_TEMPLATE SET NAME=?, DESCRIPTION=?, CATAGORY=?, CONTENT=?, MODIFIED_TIME=? WHERE ID = ?";
				runner.update(conn, sql, theTemplate.getName(), theTemplate.getDescription(), theTemplate.getCatagory(), theTemplate.getContent(),
						theTemplate.getModifiedTime(), theTemplate.getId());
			}
		} catch (Exception ex) {
			throw new GenException(ex, "保存模版时，发生异常！");
		}
	}

	public void delete(Connection conn, String id) {
		String sql;
		QueryRunner runner = new QueryRunner();

		sql = "DELETE FROM GEN_TEMPLATE WHERE ID = ?";
		try {
			runner.update(conn, sql, id);
		} catch (Exception ex) {
			throw new GenException(ex, "删除模板时，发生异常！模板ID=" + id + "！");
		}
	}

	/**
	 * 导出Json格式的模版。
	 * 
	 * @param out
	 * @param theTemplate 模版
	 */
	public void exportJson(OutputStream out, Template theTemplate) {
		this.exportJson(out, new Template[]{theTemplate});
	}
	
	/**
	 * 导出Json格式的模版。
	 * 
	 * @param out
	 * @param array 模版列表
	 */
	public void exportJson(OutputStream out, Template[] array){
		try {
			out.write(new JSONArray(array).toString().getBytes());
		} catch (Exception ex) {
			throw new GenException(ex, "导出模版时，发生异常！");
		}
	}
	
	/**
	 * 导入Json格式的模版。
	 * 
	 * @param in
	 * @return
	 */
	public Template[] importJson(InputStream in){
		try {
			byte[] buffer = new byte[in.available()];
			in.read(buffer);
			JSONArray array = new JSONArray(new String(buffer));
			
			Template[] tarray = new Template[array.length()];
			for(int i=0; i<array.length(); i++){
				JSONObject jsonobj = (JSONObject)array.get(i);
				tarray[i] = (Template)GenUtils.json2model(jsonobj, Template.class);
			}
			
			return tarray;
		} catch (Exception ex) {
			throw new GenException(ex, "导入模版时，发生异常！");
		}
	}
}
